﻿using Autofac;
using PLC.Interface.BaseUsers;
using PLCWpfTest.Common;
using PLCWpfTest.Common.Extensions;
using PLCWpfTest.ViewModels;
using System.Windows.Controls;
using YWM;

namespace PLCWpfTest.Views
{
    /// <summary>
    /// UserManagementPage.xaml 的交互逻辑
    /// </summary>
    public partial class UserManagementPage : Page
    {
        private UserManagementViewModel _userManagementViewModel;

        public UserManagementPage()
        {
            InitializeComponent();
            DataContext = _userManagementViewModel = YApp.Resolve<UserManagementViewModel>();
        }

        private async void AddButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UserOperationWindow userOperationWindow = YApp.Resolve<UserOperationWindow>(new NamedParameter(Constant.DTO_BASE_USER, null));
            if (userOperationWindow.ShowDialog() == true)
            {
                await _userManagementViewModel.SearchAsync();
            }
        }

        private async void EditButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (UserDataGrid.SelectedValue == null)
            {
                this.ShowWarning("请选择一行编辑");
                return;
            }
            BaseUserResultDto baseUser = (BaseUserResultDto)UserDataGrid.SelectedValue;
            if (!CanOperate(baseUser))
            {
                return;
            }
            UserOperationWindow userOperationWindow = YApp.Resolve<UserOperationWindow>(new NamedParameter(Constant.DTO_BASE_USER, baseUser));
            if (userOperationWindow.ShowDialog() == true)
            {
                await _userManagementViewModel.SearchAsync();
            }
        }


        private void ChangePwdButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (UserDataGrid.SelectedValue == null)
            {
                this.ShowWarning("请选择一行操作");
                return;
            }
            BaseUserResultDto baseUser = (BaseUserResultDto)UserDataGrid.SelectedValue;
            if (!CanOperate(baseUser))
            {
                return;
            }
            UserPasswordWindow userPasswordWindow = YApp.Resolve<UserPasswordWindow>(new NamedParameter("id", baseUser.Id));
            userPasswordWindow.ShowDialog();
        }

        private bool CanOperate(BaseUserResultDto baseUser)
        {
            if (!DataCache.LoginUserInfo.Account.Equals(Constant.ADMIN) && baseUser.Account.Equals(Constant.ADMIN))
            {
                this.ShowWarning("无权操作超级管理员");
                return false;
            }
            return true;
        }
    }
}
